package com.example.test.api.impl;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.example.test.HomeDo;
import com.example.test.User;
import com.example.test.UserAddress;
import com.example.test.api.UserRest;
import com.example.test.contract.CreateUserAddressParams;
import com.example.test.contract.QueryUserParams;
import com.example.test.dao.HomeRepository;
import com.example.test.dao.UserAddressRepository;
import com.example.test.dao.UserDao;
import com.example.test.service.UserService;
import com.example.test.suppert.base.exception.BusinessException;
import com.example.test.suppert.base.exception.ExpectedException;
import com.example.test.suppert.base.exception.UnexpectedException;
import com.example.test.suppert.base.result.BaseResult;
import com.example.test.suppert.base.result.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by lsl on 2021/2/24.
 */
@Slf4j
@Service
public class UserRestImpl implements UserRest {

    @Autowired
    private UserService userService;
    @Autowired
    private UserAddressRepository userAddressRepository;
    @Autowired
    private HomeRepository homeRepository;
    @Autowired
    private UserDao userDao;

    @Override
    public BaseResult<String> test() {
        return BaseResult.success("success");
    }

    @Override
    public boolean create(String name) {
        return userService.createUser(name);
    }

    @Override
    public BaseResult<String> queryAllUser() {
        List<User> users = userService.queryAllUser();
        StringBuilder resultStr = new StringBuilder();
        users.forEach(e -> resultStr
                .append(e.getId())
                .append(" | ")
                .append(e.getName())
                .append(" | ")
                .append(e.getPassword())
                .append("<br/>"));
        User user = userDao.getById(1);
        log.info("user obj: {}", user);
        return BaseResult.success(resultStr.toString());
//        return new BaseResult<>(resultStr.toString());
    }

    @Override
    public BaseResult<List<User>> queryUser(QueryUserParams params) {
        if (params == null) {
            return BaseResult.error("Not found user!");
        }
        if ("1".equals(params.getName())) {
            return BaseResult.error("报错原因1");
        } else if ("2".equals(params.getName())) {
            return BaseResult.error(Collections.emptyList());
        } else if ("3".equals(params.getName())) {
            return BaseResult.error("ERROR", "失败原因");
        } else if ("4".equals(params.getName())) {
            User build = User.builder().name("4").build();
            return BaseResult.error(Arrays.asList(build, build), "10001", "报错4");
        } else if ("5".equals(params.getName())) {
            return BaseResult.error(ErrorCode.SYSTEM_BUSY);
        } else if ("6".equals(params.getName())) {
            throw new BusinessException("业务异常");
        } else if ("7".equals(params.getName())) {
            throw new UnexpectedException("未知异常");
        } else if ("8".equals(params.getName())) {
            throw new ExpectedException("可预知异常");
        } else if ("9".equals(params.getName())){
            throw new RuntimeException("运行时异常");
        }

        User user = User.builder()
                .id(params.getId())
                .name(params.getName())
                .createDate(params.getCreateDate())
                .updateDate(params.getUpdateDate())
                .build();
        List<User> users = userService.queryUser(user);
//        StringBuilder result = new StringBuilder();
//        users.forEach(e -> result
//                .append(e.getId())
//                .append(" | ")
//                .append(e.getName())
//                .append(" | ")
//                .append(e.getPassword())
//                .append("<br/>"));
        return BaseResult.success(users);
    }

    @Override
    public User queryUserById(Long id) {
        List<User> users = userService.queryUser(User.builder().id(id).build());
        HomeDo homeDo = new HomeDo();
        homeDo.setName("aogja");
        homeRepository.save(homeDo);
        if (id == 2L) {
            homeDo.setName("adgc");
            homeRepository.saveAndFlush(homeDo);
        }
        return users.get(0);
    }

    @Override
    @Transactional
    public BaseResult<UserAddress> createUserAddress(CreateUserAddressParams params) {
        List<User> users = userService.queryUser(User.builder().id(params.getUserId()).build());
        if (CollectionUtils.isEmpty(users)) {
            return BaseResult.error("新增失败，找不到用户");
        }
        UserAddress address = UserAddress.builder()
                .userId(params.getUserId())
                .address(params.getAddress())
                .createDate(new Date())
                .build();
        UserAddress save = userAddressRepository.save(address);

        List<UserAddress> userAddressList = userAddressRepository
                .findAll(Example.of(UserAddress.builder().userId(params.getUserId()).build()));
        User updateUser = users.get(0);
        updateUser.setAddressCount(userAddressList.size());
        userService.updateUser(updateUser);
        return BaseResult.success(save);
    }
}
